<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\PriDeviceInfo;
use App\Models\Devicecontrol;
use App\Models\Devicecontrolparam;
use DB;
use ActionLog;
use App\Http\Traits\UserPrivilege;


/**
 * 控制管理 
 */
class DhControlController extends Controller
{
    use UserPrivilege;

    const UPS_DP_ID = "1258974";
    
    //计算deviceparam dp_id
    private function getCommandId($dpId, $dcmup=6) {
        return $dpId - 65536 * $dcmup;
    }
    
    /**
     * 保存命令
     * @param Request $request
     * @param type $pdi
     * @return type
     */
    public function saveCommand(Request $request) {
        $pdi = $request->input('pdi_index'); 

        try {
            $info = PriDeviceInfo::findOrFail($pdi);
        } catch (\Throwable $th) {
            return $this->error('该公司不存在此设备');
        }


        $dpid = self::UPS_DP_ID;

        $ret = $this->saveTo($request, $pdi, $dpid);

        if($ret) {
            ActionLog::createActionLog('release', '放电成功');
            return $this->success('设置成功');
        }else{
            return $this->error('设置失败');
        }
    }
    
    protected function checkPwd($password,$srcPassword) {
        return md5(trim($password))===$srcPassword;
    }
    //保存命令到数据库
    private function saveTo($request, $pdi, $dpid) {
        if(!$dpid) {
            return false;
        }
       $ret = false;
       DB::transaction(function () use($request, $pdi, $dpid, &$ret){
            $time = date('Y-m-d H:i:s');
            $data = [
                    'pdi_index' => $pdi,
                    'dc_datetime0'=>$time,
                    'Dc_status'=>1,
                    'dc_username'=>$request->user()->username,
                    'dc_userid'=>$request->user()->userid
            ];

            $ret1 = Devicecontrol::create($data); 
            $params = [
                'Dp_id'=> $this->getCommandId($dpid),
                'dcp_value'=>1,
                'dc_index'=>$ret1->dc_index
            ];

            $ret2 = Devicecontrolparam::create($params);


            $ret = ($ret1 && $ret2);
       });
       return $ret;
    }
}
